package com.yang.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.domain.Result;
import com.yang.domain.VO.PageVo;
import com.yang.domain.VO.UserInfoAndRoleIdsVo;
import com.yang.domain.VO.UserVo;
import com.yang.domain.entity.Role;
import com.yang.domain.entity.User;
import com.yang.domain.entity.UserRole;
import com.yang.enums.AppHttpCodeEnum;
import com.yang.exception.SystemException;
import com.yang.mapper.UserMapper;
import com.yang.service.RoleService;
import com.yang.service.UserRoleService;
import com.yang.service.UserService;
import com.yang.utils.BeanCopyUtils;
import com.yang.utils.SecurityUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;



/**
 * <p>
 *  用户表(User)表服务实现类
 * </p>
 * @author yang
 * @date 2023/5/29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleService roleService;

    @Override
    public Result userInfo() {
        //1.从Holder解析出用户id
        Long userId = SecurityUtils.getUserId();

        User user = getById(userId);

        UserVo userVo = BeanCopyUtils.copyBean(user, UserVo.class);

        return Result.okResult(userVo);
    }

    @Override
    public Result updateUserInfo(User user) {
        //进行信息修改
        updateById(user);

        return Result.okResult();
    }

    @Override
    public Result registerUser(User user) {
        //对邮箱进行非空判断
        if (!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        //对昵称进行非空判断
        if (!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对密码进行非空判断
        if (!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        //对用户名进行非空判断
        if (!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        //对数据判断是否存在
        if(userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }

        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);

        //存入数据库
        save(user);
        return Result.okResult();
    }

    @Override
    public Result findUserList(User user, Integer pageNum, Integer pageSize) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(StringUtils.hasText(user.getUserName()),User::getUserName,user.getUserName());
        wrapper.eq(StringUtils.hasText(user.getPhonenumber()),User::getPhonenumber,user.getPhonenumber());
        wrapper.eq(StringUtils.hasText(user.getStatus()),User::getStatus,user.getStatus());

        Page<User> page = new Page<>(pageNum,pageSize);
        page(page,wrapper);

        List<User> userList = page.getRecords();
        List<UserVo> userVoList = userList.stream()
                                       .map(u -> BeanCopyUtils.copyBean(u, UserVo.class))
                                       .collect(Collectors.toList());

        PageVo pageVo = new PageVo(userVoList,page.getTotal());

        return Result.okResult(pageVo);
    }

    @Override
    public Result checkAndAddUser(User user) {
        //1.用户不能为空
        if (!StringUtils.hasText(user.getUserName())){
            return Result.errorResult(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        //2.用户必须未存在
        LambdaQueryWrapper<User> userNameWrapper = new LambdaQueryWrapper<>();
        userNameWrapper.eq(User::getUserName,user.getUserName());
        if (count(userNameWrapper) > 0){
            return Result.errorResult(AppHttpCodeEnum.USERNAME_EXIST);
        }

        //3.手机号之前必须未存在
        LambdaQueryWrapper<User> passWordWrapper = new LambdaQueryWrapper<>();
        passWordWrapper.eq(User::getPhonenumber,user.getPhonenumber());
        if (count(passWordWrapper) > 0){
            return Result.errorResult(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }

        //4.邮箱之前之前必须为存在
        LambdaQueryWrapper<User> emailWrapper = new LambdaQueryWrapper<>();
        emailWrapper.eq(User::getEmail,user.getEmail());
        if (count(emailWrapper) > 0){
            return Result.errorResult(AppHttpCodeEnum.EMAIL_EXIST);
        }

        return addUser(user);
    }

    @Override
    public Result deleteUser(List<Long> userIds) {

        if (userIds.contains(SecurityUtils.getUserId())){
            return Result.okResult(500,"不能删除当前登录的用户");
        }
        removeByIds(userIds);

        return Result.okResult();
    }

    @Override
    public Result getUserInfo(Long userId) {
        //1.查询出用户信息和所有角色信息
        User user = getById(userId);
        List<Role> roles = roleService.selectRoleAll();

        //2.查询出用户和角色的关联表
        List<Long> roleIds = roleService.selectRoleIdByUserId(userId);

        //3.进行返回数据的封装
        UserInfoAndRoleIdsVo vo = new UserInfoAndRoleIdsVo(user,roles,roleIds);

        //4.返回
        return Result.okResult(vo);
    }

    @Override
    @Transactional
    public Result updateUser(User user) {

        //1.先更新用户信息
        updateById(user);

        //2.在删除用户角色关联表
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,user.getId());
        userRoleService.remove(wrapper);

        //3.重新添加用户角色关联表
        for (Long roleId : user.getRoleIds()) {
            UserRole userRole = new UserRole(user.getId(),roleId);
            userRoleService.save(userRole);
        }

        return Result.okResult();

    }

    private Result addUser(User user) {
        //1.对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //2.新增用户
        save(user);
        //3.如果有关联用户，则添加关联用户
        if (user.getRoleIds()!=null && user.getRoleIds().length > 0){
            insertUserRole(user);
        }
        return Result.okResult();
    }

    private void insertUserRole(User user) {

        List<UserRole> sysUserRoles = Arrays.stream(user.getRoleIds())
                .map(roleId -> new UserRole(user.getId(), roleId)).collect(Collectors.toList());
        userRoleService.saveBatch(sysUserRoles);
    }

    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(User::getNickName,nickName);

        int count = count(queryWrapper);

        return count > 0;
    }

    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(User::getUserName,userName);

        int count = count(queryWrapper);

        return count > 0;
    }


}
